//
//  NotificationManager.swift
//  TomatoClock
//
//  Created by DaleGuo on 2023/10/30.
//

import Foundation
import UserNotifications



class NotificationHandler {
    public static let Notification = NotificationHandler()

    init() {
        askPermission()
    }

    func askPermission() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { success, error in
            if success {
                print("Access Notif")
            } else if let error = error {
                print(error.localizedDescription)
            }
        }
    }

    func sendTomatoNotification(tomatoDate: Date) {
        let content = UNMutableNotificationContent()
        content.title = "Time is up"
        content.body = "Congraud!!🥳"
        content.sound = UNNotificationSound.default
        
        // 为了AppleWatch的带view通知
        content.categoryIdentifier = "WatchNotification"
        let userNotificationCenter = UNUserNotificationCenter.current()
        let category = UNNotificationCategory(identifier: "WatchNotification", actions: [], intentIdentifiers: [], options: [])
        userNotificationCenter.setNotificationCategories([category])
        
        let dateComponents = Calendar.current.dateComponents([.second, .minute, .hour, .day, .month, .year, .calendar], from: tomatoDate)

//        print(dateComponents)

        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

//        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
            
       
        
        
        userNotificationCenter.add(request) { error in
            if let error = error {
                print("Failed to schedule notification: \(error)")
            } else {
//                print("Notification scheduled successfully")
            }
        }
    }
    
    
    

    func cancelNotification() {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().removeAllDeliveredNotifications() // 直接取消所有
//        print("取消所有通知")
    }
}
